package org.wattdepot.cli.command;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Returns the total amount of carbon (or energy) emitted by this source for the given day.
 * 
 * @author Anthony Xu & John Mack
 *
 */
public class ListTotalCommand implements WattDepotCliCommand {

  /**
   * Prints a table summarizing the public sources in the system, one per line.
   * 
   * @param cli WattDepotClient with hostUri = http://server.wattdepot.org:8182/wattdepot/
   * @param commands user's command line input
   * @return string to output
   */
  public String doCommand(CommandLineInterface cli, List<String> commands) {
    String ret = "";
    String choice = commands.get(1);
    String source = commands.get(2);
    String day = commands.get(4);
    String sample = commands.get(6);
    XMLGregorianCalendar start = null;
    XMLGregorianCalendar end = null;

    try {
      start = Tstamp.makeTimestamp(day);
      end = Tstamp.incrementDays(start, 1);
      end = Tstamp.incrementMinutes(end, -1);
    }
    catch (Exception e) {
      System.out.println("Cannot print timestamp");
    } // end catch
    try {
      int samplingInterval = Integer.parseInt(sample);
      if (choice.equalsIgnoreCase("carbon")) {
      double carbonEmitted = cli.getClient().getCarbonEmitted(source, start, end, samplingInterval);
      ret = ret + "Carbon: " + carbonEmitted;
      }
      else {
        double energyEmitted =
          cli.getClient().getEnergyGenerated(source, start, end, samplingInterval);
        ret = ret + "Energy: " + energyEmitted;
      }
    }
    catch (NotAuthorizedException e) {
      System.err.println("Not authorized to view source.");
    }
    catch (ResourceNotFoundException e) {
      System.err.println("Source name not found.");
    }
    catch (BadXmlException e) {
      System.err.println("Server provided bad XML: " + e.toString());
    }
    catch (MiscClientException e) {
      System.err.println("Problem encountered with server: " + e.toString());
    }
 
    return ret;
  }
  
}
